(function () {
  'use strict';

  angular.module('BlurAdmin')
    .controller('InsertTableModalInstanceController', InsertTableModalInstanceController);

  /** @ngInject */
  function InsertTableModalInstanceController($scope, $uibModalInstance, alertService) {

    // Gets converted by createTable
    $scope.newtable = {};

    $scope.colSet = [];

    $scope.setCol = function (col) {
      if (col > 1) {
        for (var idxCol = 0; idxCol < col; idxCol++) {
          $scope.colSet.push({id: (idxCol + 1)})
        }
      }
      else {
        $scope.colSet = [{width: 100}]
      }
    };

    function createTable(tableParams) {
      if(angular.isNumber(tableParams.row) && angular.isNumber(tableParams.col)
        && tableParams.row > 0 && tableParams.col > 0){
        // TODO:: Feature in future
        //var table = "<table class='table no-border "
        //  + (tableParams.style ? "border-" + tableParams.style : '')
        //  + "'>";
        var table = "<table class='table table-bordered'>";
        // var colWidth = 100/tableParams.col;
        for (var idxRow = 0; idxRow < tableParams.row; idxRow++) {
          var row = "<tr>";
          for (var idxCol = 0; idxCol < tableParams.col; idxCol++) {
            row += "<td"
              + (idxRow == 0 ? ' style="width: ' + $scope.colSet[idxCol].width + '%;"' : '')
              +">&nbsp;</td>";
          }
          table += row + "</tr>";
        }
        return table + "</table>";
      }
    }

    /* Future feature
     $scope.tablestyles = [
     { name: 'Dotted', value: 'dotted' },
     { name: 'Dashed', value: 'dashed' },
     { name: 'Solid', value: 'solid' },
     { name: 'Double', value: 'double' },
     { name: 'Groove', value: 'groove' },
     { name: 'Ridge', value: 'ridge' },
     { name: 'Inset', value: 'inset' },
     { name: 'Outset', value: 'outset' }];
     */

    $scope.ok = function () {
      if ($scope.validation()) {
        $uibModalInstance.close(createTable($scope.newtable));
      }
    };

    $scope.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };

    $scope.validation = function () {
      var total = 0;
      angular.forEach($scope.colSet, function (item) {
        total = total + item.width
      });
      console.log(total);
      if (total !== 100) {alertService.warning('请保证所有列宽之和是100%'); return false;}

      return true
    }


  }

})();
